<template>
	<view class="calendar-container">
		<!-- 日历头部 -->
		<view class="calendar-header">
			<view class="header-left">
				<text class="current-month">{{ currentMonth }}</text>
			</view>
			<view class="header-right">
				<view class="nav-btn" @click="prevMonth">
					<image :src="`${$ImgBaseUrl}prevMonth-icon.png`" mode="aspectFit"></image>
				</view>
				<view class="nav-btn2" @click="nextMonth">
					<image :src="`${$ImgBaseUrl}nextMonth-icon.png`" mode="aspectFit"></image>
				</view>
			</view>
		</view>

		<!-- 日历主体 -->
		<view class="calendar-body">
			<!-- 星期标题 -->
			<view class="week-header">
				<view class="week-day" v-for="day in weekDays" :key="day">{{ day }}</view>
			</view>

			<!-- 日期格子 -->
			<view class="month-days">
				<view v-for="(day, index) in days" :key="index" class="day-cell" :class="{
            'current-month': day.isCurrentMonth,
            'today': day.isToday,
            'selected': day.isSelected,
            'positive-amount': day.isPositiveAmount,
            'negative-amount': day.isNegativeAmount
          }" @click="selectDate(day)">
					<text class="day-number">{{ day.day }}</text>
					<text class="day-info"
						:class="{'positive-text': day.isPositiveAmount, 'negative-text': day.isNegativeAmount}"
						v-if="day.info">{{ day.info }}</text>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		options: {
			styleIsolation: 'shared',
		},
	}
</script>

<script setup>
	import {
		ref,
		computed,
		watch,
		onMounted
	} from 'vue'

	const props = defineProps({
		initialDate: {
			type: String,
			default: () => {
				const date = new Date()
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
			}
		},
		localTime: {
			type: Array,
			default: () => []
		}
	})

	const emit = defineEmits(['dateChange', 'monthChange'])

	// 星期标题
	const weekDays = ['日', '一', '二', '三', '四', '五', '六']

	// 日历核心状态
	const currentDate = ref('')
	const currentMonth = ref('')
	const selectedDate = ref('')
	const year = ref(new Date().getFullYear())
	const month = ref(new Date().getMonth() + 1)

	// 初始化月份显示
	const updateMonthDisplay = () => {
		currentMonth.value = `${year.value}年${month.value}月`
	}

	// 生成当月日历数据
	const days = computed(() => {
		const firstDay = new Date(year.value, month.value - 1, 1)
		const lastDay = new Date(year.value, month.value, 0)
		const daysInMonth = lastDay.getDate()
		const firstDayOfWeek = firstDay.getDay()

		// 上个月的最后几天
		const prevMonthLastDay = new Date(year.value, month.value - 1, 0).getDate()
		const prevMonthDays = []
		for (let i = firstDayOfWeek - 1; i >= 0; i--) {
			prevMonthDays.push({
				day: prevMonthLastDay - i,
				isCurrentMonth: false,
				date: `${year.value}-${String(month.value - 1).padStart(2, '0')}-${String(prevMonthLastDay - i).padStart(2, '0')}`
			})
		}

		// 当前月的天数
		const currentMonthDays = []
		for (let i = 1; i <= daysInMonth; i++) {
			const dateStr = `${year.value}-${String(month.value).padStart(2, '0')}-${String(i).padStart(2, '0')}`
			const today = new Date()
			const isToday = today.getFullYear() === year.value &&
				today.getMonth() + 1 === month.value &&
				today.getDate() === i

			// 查找是否有对应的标记数据
			const marker = props.localTime.find(item => item.localDate === dateStr)

			currentMonthDays.push({
				day: i,
				isCurrentMonth: true,
				date: dateStr,
				isToday,
				isSelected: selectedDate.value === dateStr,
				info: marker ? (marker.amount > 0 ? `${marker.amount}` : '—') : null,
				isPositiveAmount: marker && marker.amount > 0,
				isNegativeAmount: marker && marker.amount <= 0
			})
		}

		// 下个月的前几天
		const nextMonthDays = []
		const totalCells = Math.ceil((prevMonthDays.length + daysInMonth) / 7) * 7
		const remainingCells = totalCells - (prevMonthDays.length + daysInMonth)
		for (let i = 1; i <= remainingCells; i++) {
			nextMonthDays.push({
				day: i,
				isCurrentMonth: false,
				date: `${year.value}-${String(month.value + 1).padStart(2, '0')}-${String(i).padStart(2, '0')}`
			})
		}

		return [...prevMonthDays, ...currentMonthDays, ...nextMonthDays]
	})

	// 月份切换逻辑
	const prevMonth = () => {
		month.value--
		if (month.value < 1) {
			month.value = 12
			year.value--
		}
		updateMonthDisplay()
		emit('monthChange', {
			year: year.value,
			month: month.value
		})
	}

	const nextMonth = () => {
		month.value++
		if (month.value > 12) {
			month.value = 1
			year.value++
		}
		updateMonthDisplay()
		emit('monthChange', {
			year: year.value,
			month: month.value
		})
	}

	// 选择日期
	const selectDate = (day) => {
		if (!day.isCurrentMonth) return

		selectedDate.value = day.date
		const [y, m, d] = day.date.split('-').map(Number)
		emit('dateChange', {
			fullDate: day.date,
			year: y,
			month: m,
			day: d
		})
	}

	// 监听localTime变化
	watch(() => props.localTime, () => {
		// 数据变化会自动触发days计算属性的更新
	}, {
		deep: true
	})

	// 初始化
	onMounted(() => {
		const initDate = new Date(props.initialDate)
		if (!isNaN(initDate.getTime())) {
			year.value = initDate.getFullYear()
			month.value = initDate.getMonth() + 1
			selectedDate.value = props.initialDate
		}
		updateMonthDisplay()
	})

	// 暴露方法
	defineExpose({
		setDate(date) {
			const dateObj = new Date(date)
			if (!isNaN(dateObj.getTime())) {
				year.value = dateObj.getFullYear()
				month.value = dateObj.getMonth() + 1
				selectedDate.value = date
				updateMonthDisplay()
			}
		}
	})
</script>

<style lang="scss" scoped>
	.calendar-container {
		background-color: #fff;
		border-radius: 20rpx;
		overflow: hidden;
		// height: 880rpx;
	}

	.calendar-header {
		display: flex;
		align-items: center;
		padding: 20rpx;
		background: #fff;
		height: 80rpx;
		background: linear-gradient(180deg, #FFFFFF 0%, #EAF3FF 100%) !important;


		.header-left {
			.current-month {
				font-size: 32rpx;
				font-weight: 500;
				color: #333;
			}
		}

		.header-right {
			display: flex;
			align-items: center;

			.nav-btn {
				margin-left: 20rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background: #E1EEFF;
				border-radius: 8rpx;
				width: 38rpx;
				height: 38rpx;
				padding: 10rpx;
				box-sizing: border-box;

				image {
					width: 13rpx;
					height: 20rpx;
				}
			}

			.nav-btn2 {
				margin-left: 20rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				background: #E5EAF0;
				border-radius: 8rpx;
				width: 38rpx;
				height: 38rpx;
				padding: 10rpx;
				box-sizing: border-box;

				image {
					width: 13rpx;
					height: 20rpx;
				}
			}
		}
	}

	// 日历主体样式
	.calendar-body {
		padding: 20rpx 10rpx;
		
	}

	.week-header {
		display: flex;
		justify-content: space-around;
		height: 60rpx;
		// background-color: #f5f5f5;
		align-items: center;
		padding: 0 15rpx;
		margin-bottom: 20rpx;

		.week-day {
			width: calc((100% - 60rpx) / 7);
			/* 与日期格子同宽 */
			text-align: center;
			font-size: 30rpx;
			color: #999;

		}
	}

	.month-days {
		display: flex;
		flex-wrap: wrap;
		flex-wrap: wrap;
		padding: 0 15rpx;
		/* 两侧留白 */
		justify-content: space-between;
		/* 均匀分布 */
	}

	.day-cell {
		width: calc((100% - 60rpx) / 7);
		/* 假设总共7列，间距总和60rpx */
		height: 90rpx;
		margin-bottom: 10rpx;
		/* 底部间距 */
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 8rpx;
		/* 上边距10rpx，左右边距5rpx */

		.day-number {
			font-size: 26rpx;
			color: #333;
		}

		.day-info {
			font-size: 18rpx;
			margin-top: 4rpx;

			// color: #999;
			&.positive-text {
				color: #FF6A47;
			}

			&.negative-text {
				color: #999999;
			}

		}

		// 非当前月样式
		&:not(.current-month) {

			.day-number,
			.day-info {
				color: #999;
			}
		}

		// 今天样式
		&.today {
			.day-number {
				color: #FF6A47;
				font-weight: bold;
			}
		}

		// 选中样式
		&.selected {
			// background-color: #E6F1FF !important;
		}

		// 正数金额样式
		&.positive-amount {
			background: #FFEBE6;
		}

		// 负数金额样式
		&.negative-amount {
			background: #E6F1FF;
		}
	}
</style>